﻿using System;
using System.Collections.Generic;
using System.Text;
using Vortex.Drawing;

namespace Vortex.SceneFramework {

	/// <summary>
	/// Simple text element. It draws layouted text relative to element origin point.
	/// </summary>
	public class TextElement : ContentElement, ITextNode {
		///<summary>Contains information about last rendered text rectangle</summary>
		private Rect _textRenderRegion;

		private string _text;
		private SpriteFont _font;
		private TextLayout _layout;

		public TextElement() {
			_font = SpriteFont.Default;
			Color = ColorU.Blank;
		}

		/// <summary>
		/// Gets or sets the text of this element.
		/// </summary>
		/// <value>The text of element.</value>
		public virtual string Text {
			get { return _text; }
			set { 
				_text = value;
				_textRenderRegion = Rect.Empty;
			}
		}

		/// <summary>
		/// Gets or sets the sprite font to use for text renderering.
		/// </summary>
		/// <value>The sprite font.</value>
		public SpriteFont Font {
			get { return _font; }
			set {
				_font = value;
				_textRenderRegion = Rect.Empty;
			}
		}

		/// <summary>
		/// Gets or sets the layout of text relative to element origin.
		/// </summary>
		/// <value>The text layout relative to element origin.</value>
		public TextLayout Layout {
			get { return _layout; }
			set { _layout = value; }
		}

		/// <summary>
		/// Gets the bounding box of text element in local coordinates. TextElement implements render calculation
		/// </summary>
		/// <value>The bounding box of text element.</value>
		public override Rect BoundingBox {
			get { return _textRenderRegion; }
		}

		/// <summary>
		/// Draws the text element content.
		/// </summary>
		/// <param name="canvas">The canvas to use for element drawing.</param>
		protected override void Draw(Canvas2D canvas) {
			SpriteFont font = Font ?? SpriteFont.Default;
			if (!string.IsNullOrEmpty(Text)) {
				Vector2 textSize = Canvas2D.MeasureText(Font, Text);
				Vector2 textPosition = Vector2.Zero;

				//calculate text position
				TextLayout layout = Layout;
				if ((layout & TextLayout.Right) == TextLayout.Right) {
					textPosition.X = -textSize.X * ((layout & TextLayout.Left) == TextLayout.Left ? 0.5f : 1f);
				}
				if ((layout & TextLayout.Bottom) == TextLayout.Bottom) {
					textPosition.Y = -textSize.Y * ((layout & TextLayout.Top) == TextLayout.Top ? 0.5f : 1f);
				}

				//calculate text region by alignment
				_textRenderRegion = Rect.FromBox(
					textPosition.Floored,
					textSize
				);

				//draw text with blending
				using (canvas <= Blending) {
					canvas.DrawTextLayout(font, _textRenderRegion, Text, layout, ContentColor);					
				}
			}
		}
	}

}
